package Client;

import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;

/**
 * This abtract class have host name
 * and port to make a connection with Server
 * @author Group 6
 */
public abstract class NetworkClient {
	private String host;
	private int port;

	/**
	 * Register host and port. The connection won't actually be established
	 * until you call connect.
	 */
	public NetworkClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	/**
	 * Create a socket via using host name and port
	 * and call handle connection to connect server
	 */
	public void connect() {
		try {
			Socket client = new Socket(host, port);
			handleConnection(client);
			client.close();
		} catch (UnknownHostException uhe) {
			System.out.println("Unknown host: " + host);
			uhe.printStackTrace();
		} catch (IOException ioe) {
			System.out.println("IOException: " + ioe);
			ioe.printStackTrace();
		}
	}

	/**
	 * This is the method you will override when making a network client for
	 * your task.
	 */
	protected abstract void handleConnection(Socket client) throws IOException;

	/**
	 * @return the host name of the connection
	 */
	public String getHost() {
		return host;
	}

	/**
	 * @return the port number of the connection
	 */
	public int getPort() {
		return port;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "NetworkClient [host=" + host + ", port=" + port + "]";
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((host == null) ? 0 : host.hashCode());
		result = prime * result + port;
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof NetworkClient))
			return false;
		NetworkClient other = (NetworkClient) obj;
		if (host == null) {
			if (other.host != null)
				return false;
		} else if (!host.equals(other.host))
			return false;
		if (port != other.port)
			return false;
		return true;
	}
	

}
